package com.springboot.framework.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.springboot.framework.config.AppConfig;
import com.springboot.framework.exception.BusinessException;
import com.springboot.framework.service.MapService;
import com.springboot.framework.utils.ToolsUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author SWF
 * @date 2019/6/18 16:10
 **/
@Service
public class MapServiceImpl implements MapService {
    @Resource
    private AppConfig appConfig;

    private static final Logger logger = LoggerFactory.getLogger(MapServiceImpl.class);

    /**
     * 地址解析为经纬度
     *
     * @param address
     * @return
     */
    @Override
    public Map addressToGeocoder(String address) {
        String url = "https://apis.map.qq.com/ws/geocoder/v1/";
        String jsonStrToken = ToolsUtil.sendGet(url, "address=" + address + "&key=" + appConfig.getTencentMapKey());
        Map map = new HashMap();
        try {
            JSONObject jsonObject = JSON.parseObject(jsonStrToken).getJSONObject("result");
            JSONObject location = jsonObject.getJSONObject("location");
            logger.info("【地址解析】经度：{}，纬度：{}，地址：{}", location.getString("lng"), location.getString("lat"), address);
            map.put("longitude", location.getString("lng"));
            map.put("latitude", location.getString("lat"));
        } catch (NullPointerException e) {
            logger.error("【地址解析】地址解析出错，请输入正确地址并重试。{}",address);
            throw new BusinessException("地址解析出错,请输入正确地址并重试");
        }
        return map;
    }

    /**
     * 经纬度解析为地址
     *
     * @param longitude
     * @param latitude
     * @return
     */
    @Override
    public Map geocoderToAddress(String longitude, String latitude) {
        return null;
    }
}
